package com.gmlive.common.sample.views

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.os.Build
import android.util.AttributeSet
import android.util.Log
import android.view.View
import com.gmlive.common.sample.R

/**
 *
 * @Author Sven
 * @Date 2021/8/6
 * @Email jiangzhimin@inke.cn
 */
@SuppressLint("UseCompatLoadingForDrawables")
class MatchButtonBackgroundView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val imagePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        color = 0xFFF5B4FF.toInt()
        maskFilter = BlurMaskFilter(13.px, BlurMaskFilter.Blur.INNER)
    }

    init {
        // Enable software rendering on HoneyComb and up. (needed for shadow)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            setLayerType(LAYER_TYPE_SOFTWARE, null)
        }
    }

    private var backgroundBitmap: Bitmap? = null
    private var bitmapShader: BitmapShader? = null
    private val mBounds = RectF()


    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        val drawable = context.resources.getDrawable(R.drawable.button_start_match)
        backgroundBitmap = drawableToBitmap(drawable)
        backgroundBitmap?.let {
            bitmapShader =
                BitmapShader(it, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP).also { shader ->
                    imagePaint.shader = shader
                }
        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

        mBounds.set(0F, 0F, measuredWidth.toFloat(), measuredHeight.toFloat())
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas?.let {
            if (mBounds.isEmpty) {
                return
            }

            val radius = mBounds.height()
            it.drawRoundRect(mBounds, radius, radius, imagePaint)
        }
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        if (bitmapShader != null) {
            bitmapShader = null
        }
        imagePaint.shader = null
        backgroundBitmap?.recycle()
    }

    private fun drawableToBitmap(drawable: Drawable?): Bitmap? {
        if (drawable == null) return null

        if (drawable is BitmapDrawable) return drawable.bitmap

        val intrinsicWidth = drawable.intrinsicWidth
        val intrinsicHeight = drawable.intrinsicHeight

        if (!(intrinsicWidth > 0 && intrinsicHeight > 0)) return null

        return try {
            // Create Bitmap object out of the drawable
            val bitmap =
                Bitmap.createBitmap(intrinsicWidth, intrinsicHeight, Bitmap.Config.ARGB_8888)
            val canvas = Canvas(bitmap)
            drawable.setBounds(0, 0, canvas.width, canvas.height)
            val rect = Rect(0, 0, bitmap.width, bitmap.height)
            val paint = Paint(Paint.ANTI_ALIAS_FLAG)
            paint.color = -0x1000000
            paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
            canvas.drawBitmap(bitmap, rect, rect, paint)
            drawable.draw(canvas)
            bitmap
        } catch (e: OutOfMemoryError) {
            // Simply return null of failed bitmap creations
            Log.e("MatchButtonView", "Encountered OutOfMemoryError while generating bitmap!")
            null
        }
    }
}